<template>
  <el-dialog
    v-model="show"
    title="新建安全文明内容"
    width="40vw"
    destroy-on-close
    custom-class="add-check"
    @close="handleCancel"
  >
    <el-form
      :model="formData"
      label-width="200px"
      ref="formDataRef"
      :rules="formRules"
    >
      <el-form-item
        :label="item.formTitle"
        v-for="(item, index) in formData.dynamicForms || []"
        :key="index"
      >
        <template #label>
          <p class="form-item-title">
            <span style="color: #c45656; margin-right: 4px">*</span
            >{{ item.formTitle }}
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="item.formTitleDetails"
              placement="top-start"
            >
              <i class="el-icon-question" size="24"></i>
            </el-tooltip>
          </p>
        </template>
        <ecm-image-upload
          :files="formData.dynamicForms[index]['attList']"
          @set-file="
            fileList => {
              handleChange(fileList, index);
            }
          "
        ></ecm-image-upload>

        <div v-if="tipError[index]" class="error-tip">请上传照片</div>
      </el-form-item>
      <el-form-item label="其他照片" prop="otherAttachment">
        <ecm-image-upload
          :files="formData.otherAttachment"
          @set-file="
            fileList => {
              handleChange(fileList, 'other');
            }
          "
        ></ecm-image-upload>
      </el-form-item>
      <el-form-item label="检查小结">
        <el-input
          type="textarea"
          v-model="formData.ext1"
          :rows="3"
          maxlength="500"
        ></el-input>
      </el-form-item>
      <el-form-item label="项目执行组(专业组组长)" prop="partybHandlerInfo">
        <el-select
          v-model="formData.partybHandlerInfo"
          filterable
          clearable
          remote
          placeholder="请输入姓名搜索"
          :remote-method="getUserData"
          value-key="value"
          style="width: 100%"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSure" :loading="sureLoading"
          >保存</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRef, toRefs } from "vue";
import { storageLocal } from "/@/utils/storage";
import { getUserList } from "/@/api/user";
import ecmImageUpload from "/@/components/ecmImage/index.vue";
import {
  acceptImageTypes,
  uploadUrl,
  uploadHeaders,
  handlePreview,
  handleError,
  beforeAvatarUpload
} from "/@/utils/file";

export default defineComponent({
  name: "startCheck",
  components: {
    ecmImageUpload
  },
  props: {
    checkItem: {
      type: Object,
      default: () => {}
    },
    sureLoading: {
      type: Boolean,
      default: false
    }
  },
  emits: ["handleCancel", "handleSure"],
  setup(props, { emit }) {
    const show = ref(true);
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const checkItemProp = toRef(props, "checkItem");
    const dynamicForms =
      checkItemProp.value.dynamicForms &&
      JSON.parse(checkItemProp.value.dynamicForms);
    const state = reactive({
      formData: {
        checkItemIds: [checkItemProp.value.id],
        ext1: "",
        remark: "", // 存放流程数据回显
        dynamicForms,
        otherAttachment: [],
        partybHandlerId: "",
        partybHandlerName: "",
        partybHandlerInfo: "" as any,
        projectName: storageLocal.getItem("projectInfo").name,
        projectManageId: storageLocal.getItem("projectInfo").id
      }
    });
    const userList = ref([]) as any; // 人员列表数据
    const tipError = ref([]) as any;
    const formRules = ref({
      partybHandlerInfo: [
        {
          required: true,
          message: "请选择项目执行组(专业组组长)",
          trigger: "change"
        }
      ]
    });
    let dynamicsOpinion = [];
    //获取项目组成员
    const getUserData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 100,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleRemove = (file, fileList, num) => {
      if (num === "other") {
        state.formData.otherAttachment = fileList;
      } else {
        state.formData.dynamicForms[num].attList = fileList;
      }
    };

    const handleChange = (fileList, num) => {
      if (num === "other") {
        state.formData.otherAttachment = fileList;
      } else {
        state.formData.dynamicForms[num].attList = fileList;
        validataDynamic(num);
      }
    };

    const handleCancel = async () => {
      emit("handleCancel");
    };

    const validataDynamic = (num?) => {
      // 校验动态表单
      let tipFlag = false;
      if (num || num === 0) {
        let item = state.formData.dynamicForms[num];
        if (!item.attList || (item.attList && item.attList.length === 0)) {
          tipError.value[num] = true;
          tipFlag = true;
        } else {
          tipError.value[num] = false;
        }
      } else {
        state.formData.dynamicForms.map((item, index) => {
          if (!item.attList || (item.attList && item.attList.length === 0)) {
            tipError.value[index] = true;
            tipFlag = true;
          } else {
            tipError.value[index] = false;
          }
        });
      }
      return tipFlag;
    };

    const handleSure = async () => {
      let tipFlag = validataDynamic();
      const isValid = await formDataRef.value.validate();
      if (!isValid || tipFlag) return;
      // 动态表单回显字段处理
      dynamicsOpinion.length = 0;
      state.formData.dynamicForms.map(item => {
        let obj = {
          name: item.formTitle,
          tips: item.formTitleDetails,
          content: item.attList,
          type: "images"
        };
        dynamicsOpinion.push(obj);
      });
      // 回显字段拼接
      state.formData.remark = JSON.stringify([
        ...dynamicsOpinion,
        {
          name: "其他照片",
          content: state.formData.otherAttachment,
          type: "images"
        },
        {
          name: "检查小结",
          content: state.formData.ext1,
          type: "textarea"
        }
      ]);
      emit("handleSure", state.formData);
    };

    return {
      formDataRef,
      formRules,
      show,
      userList,
      ...toRefs(state),
      handleCancel,
      handleSure,
      getUserData,
      uploadUrl,
      acceptImageTypes,
      uploadHeaders,
      handleChange,
      handleRemove,
      handleError,
      handlePreview,
      beforeAvatarUpload,
      tipError
    };
  }
});
</script>
<style lang="scss" scoped>
:deep .back-picture {
  .el-upload-list__item {
    width: 56px;
    height: 56px;
    .el-upload-list__item-actions {
      font-size: 18px;
    }
  }
  .el-upload--picture-card {
    width: 56px;
    height: 56px;
    background: #fdfdff;
    border-radius: 4px;
    border: 1px solid #e4e8f2;
    i {
      height: 100%;
      width: 100%;
      line-height: 100%;
      font-size: 18px;
      color: #8c939d;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      span {
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #8895b7;
      }
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
:deep .add-check {
  .el-dialog__body {
    padding: 20px 40px 8px 10px;
  }
}
.check-table {
  padding-left: 20px;
  .card-header {
    font-weight: bold;
    color: #494c53;
  }
  .el-table {
    width: 100%;
    margin: 20px 0;
  }
}

.error-tip {
  color: #e45d5d;
  font-size: 12px;
}
</style>
